import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {Content, Events, IonicPage, NavController, NavParams} from 'ionic-angular';
import {SideMenuService} from "../../../services/common/side-menu.service";
import {TabsPage} from "../../tabs/tabs";
import {PolicyFilterPage} from "../policy-filter/policy-filter";
import {PolicyListProvider} from "../../../providers/policy/policy-list/policy-list.provider";
import * as moment from 'moment';
import {LoadingService} from "../../../services/common/loading.service";

/**
 * Generated class for the PolicyListPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
    selector: 'page-policy-list',
    templateUrl: 'policy-list.html',
    providers: [SideMenuService, PolicyListProvider]
})
export class PolicyListPage {

    openRoot = (name, index) => this.openTab(name, index);
    policyList: any;
    policyNum: number = 0;
    moment = moment;
    queryParams: any;
    queryRecord: any;
    isScrolling = false;
    isArriveBottom = false;
    isLoaded: boolean = false;
    @ViewChild(Content) content: Content;

    constructor(public navCtrl: NavController,
                private sideMenuService: SideMenuService,
                private policyListProvider: PolicyListProvider,
                public tabsPage: TabsPage,
                public changeRef: ChangeDetectorRef,
                private loadingService: LoadingService,
                public events: Events,
                public navParams: NavParams) {
        // this.queryParams = this.navParams.get('condition');
        // this.queryRecord = this.navParams.get('record');
    }

    ionViewDidEnter() {
        console.log('ionViewDidEnter');
        console.log(this.events);
        let pos = 0 ;
        this.events.subscribe('policy:filter', (condition,record,flag) => {
            pos = pos + 1;

            console.log('subscribe');

            if (flag) {
                this.queryParams = condition;
                this.queryRecord = record;
                this.getPolicyList();
            }

            this.events.unsubscribe('policy:filter');
            console.log('unsubscribe1');
        });

        setTimeout(()=> {
            if(pos == 0){
                this.events.unsubscribe('policy:filter');
                console.log('unsubscribe2');
            }
        },100);
    }

    ionViewDidLoad() {
        // console.log('ionViewDidLoad');
        this.getPolicyList();

        // console.log(this.moment(545670000*1000).format('YYYY/MM/DD'))
        // console.log(this.moment(545673600*1000).format('YYYY/MM/DD'))
    }


    openMenu(myEvent) {
        this.sideMenuService.openSideMenu(myEvent)
    }

    openTab(name, index) {
        this.navCtrl.popToRoot()
        this.tabsPage.openPage({name: name, index: index});
    }

    //获取列表
    getPolicyList() {
        this.loadingService.showLoading();
        this.policyListProvider.getPolicyList(this.queryParams, '0').subscribe(res => {
            // console.log(res);
            if (res) {
                this.policyNum = res.length;
            }
            this.policyList = res;

            this.isLoaded = true;

            this.events.unsubscribe('policy:filter');

            this.loadingService.dismissLoading();
        }, error2 => {
            this.events.unsubscribe('policy:filter');
            this.loadingService.dismissLoading();
        });
    }

    getSex(sex: string): string {
        if (sex === 'M') return 'nan';
        if (sex === 'F') return 'nv';
        if (sex === '') return 'unknow';
    }

    pullDownRefresh(refresher) {
        this.policyListProvider.getPolicyList(this.queryParams, '1').subscribe(res => {
            if (res) {
                this.policyNum = res.length;
            }
            this.policyList = res;
            refresher.complete();
        }, error2 => {
            refresher.complete();
        });
    }

    get clientItemHeight(): string {
        const windowW = window['innerWidth'];
        return (windowW * 38.34 / 100) + 'px';
    }

    // goToSearch() {
    //   this.navCtrl.push('PolicySearchPage');
    // }

    goToFilter() {
        this.navCtrl.push('PolicyFilterPage', {'record': this.queryRecord});
    }

    goToDetail(policyNO: string,
               policyPayToDate: string,
               policyStatus: string,
               policyStatusCode: string,
               orphanType: string,
               agentCode: string) {
        this.navCtrl.push('PolicyDetailsPage', {
            policyNO: policyNO,
            policyPayToDate: policyPayToDate,
            policyStatus: policyStatus,
            policyStatusCode: policyStatusCode,
            orphanType: orphanType,
            agentCode: agentCode?agentCode:''
        });
    }

    goBack() {
        // this.navCtrl.pop();
        // this.navCtrl.push('HomePage');
       this.navCtrl.popToRoot();
    }

    /**
     * 跳转到投保人详情
     */
    goToHolderDetail(id) {
        this.navCtrl.push("HolderClientDetailPage", {"clientNum": id})
    }


    /**
     * 跳转到被保人详情
     */
    goToInsuredDetail(id) {
        this.navCtrl.push("HolderClientDetailPage", {"clientNum": id})
    }

    scrollStart(e) {
        this.isScrolling = true;
    }

    scrollEnd(e) {
        this.isScrolling = false;
    }

    scrolling() {
        const dimensions = this.content.getContentDimensions();
        const temp1 = dimensions.scrollHeight - dimensions.scrollTop - dimensions.contentHeight < 100;

        if (temp1 !== this.isArriveBottom) {
            this.isArriveBottom = temp1;
            this.changeRef.detectChanges();
        }
    }

    goUp() {
        if (this.isScrolling) {
            setTimeout(() => {
                this.goUp();
            }, 300);
            return;
        }
        this.content.scrollToTop();
    }
}
